const express = require('express')
const authRoutes = require('./auth')
const aiConfigRoutes = require('./aiConfig')
const chatRoutes = require('./chat')
const systemConfigRoutes = require('./systemConfig')
const studentProgressRoutes = require('./studentProgress')
const chapterConfigRoutes = require('./chapterConfig')
const chapterHighlightsRoutes = require('./chapterHighlights')
const fileUploadRoutes = require('./fileUpload')
const lectureRoutes = require('./lectures')
const { HTTP_STATUS } = require('../utils/constants')
const logger = require('../utils/logger')

const router = express.Router()

// API版本信息
router.get('/', (req, res) => {
  res.json({
    success: true,
    message: '知识库后端API服务',
    version: '1.0.0',
    timestamp: new Date().toISOString(),
    endpoints: {
      auth: '/api/auth',
      aiConfig: '/api/ai-config',
      ai: '/api/ai',
      chat: '/api/chat',
      systemConfig: '/api/system-config',
      chapterConfig: '/api/chapter-config',
      chapterHighlights: '/api/chapter-highlights',
      lectures: '/api/lectures'
    }
  })
})

// 健康检查
router.get('/health', (req, res) => {
  res.json({
    success: true,
    status: 'healthy',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    memory: process.memoryUsage(),
    version: process.version
  })
})

// 系统状态
router.get('/status', (req, res) => {
  const status = {
    success: true,
    system: {
      status: 'running',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
      memory: process.memoryUsage(),
      cpu: process.cpuUsage(),
      version: process.version,
      platform: process.platform,
      arch: process.arch
    },
    services: {
      database: 'connected', // JSON文件数据库
      logger: 'active',
      auth: 'active',
      ai: 'active'
    }
  }
  
  res.json(status)
})

// 注册路由
router.use('/auth', authRoutes)
router.use('/ai-config', aiConfigRoutes)
router.use('/chat', chatRoutes)
router.use('/system-config', systemConfigRoutes)
router.use('/student-progress', studentProgressRoutes)
router.use('/chapter-config', chapterConfigRoutes)
router.use('/chapter-highlights', chapterHighlightsRoutes)
router.use('/file', fileUploadRoutes)
router.use('/lectures', lectureRoutes)

// 添加直接的 chapters 路由，重定向到 lectures/chapters
const LectureController = require('../controllers/lectureController')
router.get('/chapters', LectureController.getAllChaptersWithLectures)

// API文档路由（简单版本）
router.get('/docs', (req, res) => {
  const apiDocs = {
    success: true,
    title: '知识库后端API文档',
    version: '1.0.0',
    baseUrl: '/api',
    endpoints: {
      authentication: {
        prefix: '/auth',
        routes: [
          { method: 'POST', path: '/register', description: '用户注册' },
          { method: 'POST', path: '/login', description: '用户登录' },
          { method: 'POST', path: '/refresh', description: '刷新令牌' },
          { method: 'POST', path: '/logout', description: '用户登出' },
          { method: 'PUT', path: '/password', description: '修改密码' },
          { method: 'POST', path: '/password/reset-request', description: '请求密码重置' },
          { method: 'POST', path: '/password/reset', description: '重置密码' },
          { method: 'GET', path: '/me', description: '获取当前用户信息' },
          { method: 'POST', path: '/verify', description: '验证令牌' },
          { method: 'GET', path: '/permissions', description: '获取用户权限' },
          { method: 'POST', path: '/permissions/check', description: '检查特定权限' }
        ]
      },
      aiConfig: {
        prefix: '/ai-config',
        routes: [
          { method: 'POST', path: '/', description: '创建AI配置' },
          { method: 'GET', path: '/', description: '获取AI配置列表' },
          { method: 'GET', path: '/:configId', description: '获取单个AI配置' },
          { method: 'PUT', path: '/:configId', description: '更新AI配置' },
          { method: 'DELETE', path: '/:configId', description: '删除AI配置' },
          { method: 'PUT', path: '/:configId/default', description: '设置默认AI配置' },
          { method: 'POST', path: '/:configId/test', description: '测试AI配置连接' },
          { method: 'PUT', path: '/:configId/toggle', description: '切换AI配置状态' },
          { method: 'POST', path: '/:configId/duplicate', description: '复制AI配置' },
          { method: 'GET', path: '/default/config', description: '获取默认AI配置' },
          { method: 'GET', path: '/models/supported', description: '获取支持的AI模型' },
          { method: 'GET', path: '/providers/supported', description: '获取支持的服务提供商' },
          { method: 'POST', path: '/validate/parameters', description: '验证AI配置参数' }
        ]
      },
      chat: {
        prefix: '/chat',
        routes: [
          { method: 'POST', path: '/sessions', description: '创建聊天会话' },
          { method: 'GET', path: '/sessions', description: '获取聊天会话列表' },
          { method: 'GET', path: '/sessions/:sessionId', description: '获取聊天会话详情' },
          { method: 'PUT', path: '/sessions/:sessionId', description: '更新聊天会话' },
          { method: 'DELETE', path: '/sessions/:sessionId', description: '删除聊天会话' },
          { method: 'PUT', path: '/sessions/:sessionId/restore', description: '恢复已删除的会话' },
          { method: 'POST', path: '/sessions/:sessionId/messages', description: '发送消息' },
          { method: 'GET', path: '/sessions/:sessionId/messages', description: '获取会话消息列表' },
          { method: 'PUT', path: '/sessions/:sessionId/messages/:messageId', description: '编辑消息' },
          { method: 'DELETE', path: '/sessions/:sessionId/messages/:messageId', description: '删除消息' },
          { method: 'POST', path: '/sessions/:sessionId/messages/:messageId/reactions', description: '添加消息反应' },
          { method: 'DELETE', path: '/sessions/:sessionId/messages/:messageId/reactions', description: '移除消息反应' },
          { method: 'GET', path: '/messages/search', description: '搜索消息' },
          { method: 'GET', path: '/sessions/:sessionId/export', description: '导出会话' },
          { method: 'POST', path: '/sessions/batch', description: '批量操作会话' },
          { method: 'GET', path: '/sessions/:sessionId/stats', description: '获取会话统计信息' },
          { method: 'POST', path: '/sessions/:sessionId/tags', description: '添加会话标签' },
          { method: 'DELETE', path: '/sessions/:sessionId/tags', description: '移除会话标签' },
          { method: 'PUT', path: '/sessions/:sessionId/pin', description: '切换会话置顶状态' }
        ]
      },
      systemConfig: {
        prefix: '/system-config',
        routes: [
          { method: 'GET', path: '/:key', description: '获取系统配置' },
          { method: 'PUT', path: '/:key', description: '设置系统配置' },
          { method: 'DELETE', path: '/:key', description: '删除系统配置' },
          { method: 'GET', path: '/', description: '获取所有系统配置' },
          { method: 'POST', path: '/batch', description: '批量设置系统配置' },
          { method: 'POST', path: '/:key/reset', description: '重置配置到默认值' },
          { method: 'POST', path: '/reset/all', description: '批量重置配置到默认值' },
          { method: 'GET', path: '/export/configs', description: '导出系统配置' },
          { method: 'POST', path: '/import/configs', description: '导入系统配置' },
          { method: 'POST', path: '/:key/validate', description: '验证配置值' },
          { method: 'GET', path: '/:key/history', description: '获取配置历史记录' },
          { method: 'DELETE', path: '/cache/:key?', description: '清除配置缓存' },
          { method: 'GET', path: '/stats/overview', description: '获取配置统计信息' }
        ]
      }
    },
    authentication: {
      type: 'Bearer Token',
      header: 'Authorization: Bearer <token>',
      description: '大部分API需要在请求头中包含有效的JWT令牌'
    },
    responseFormat: {
      success: {
        success: true,
        message: 'string (optional)',
        data: 'object (optional)'
      },
      error: {
        success: false,
        message: 'string',
        error: 'string (optional)',
        code: 'string (optional)'
      }
    }
  }
  
  res.json(apiDocs)
})

// 测试路由
router.get('/test', (req, res) => {
  logger.logRequest(req, 'API测试请求')
  
  res.json({
    success: true,
    message: 'API测试成功',
    timestamp: new Date().toISOString(),
    requestInfo: {
      method: req.method,
      url: req.url,
      headers: req.headers,
      query: req.query,
      ip: req.ip,
      userAgent: req.get('User-Agent')
    }
  })
})

// 错误测试路由（仅开发环境）
if (process.env.NODE_ENV === 'development') {
  router.get('/test/error', (req, res, next) => {
    const error = new Error('这是一个测试错误')
    error.status = HTTP_STATUS.INTERNAL_SERVER_ERROR
    next(error)
  })
  
  router.get('/test/async-error', async (req, res, next) => {
    try {
      throw new Error('这是一个异步测试错误')
    } catch (error) {
      next(error)
    }
  })
}

module.exports = router